<template>
  <div class="container">


    <div class="left">
      <div class="resume-nav" style="margin: 0 50px; margin-top: 15px;display: flex; flex-direction: column; align-items: center;">
        <div class="nav-header" style="width: 100%; display: flex; align-items: center;">
          <span style="margin-left: 18px;">简历目录</span>
        </div>
        <el-menu
          :default-active="activeIndex"
          class="el-menu-vertical-demo"
          @select="handleSelect"
          style="width: 100%;"
        >
          <el-menu-item
            v-for="(resume, index) in resumes"
            :key="index"
            :index="(index + 1).toString()"
          >
            简历{{ index + 1 }}

          </el-menu-item>
          <el-divider></el-divider>
        </el-menu>
        <el-button type="primary" style="width: 100%;" @click="switchToEmptyResume">创建简历</el-button>
      </div>
    </div>



    <div class="right" >
      <div class="resume-main" style="margin-right: 150px; margin-top: 15px;">
          <div class="nav-header" style="display: flex; justify-content: space-between; align-items: center; ">
              <span style="margin-left: 18px;">我的在线简历</span>
            <div>
               <el-button type="success" @click="generatePdf">导出简历</el-button>
            </div>
          </div>
          <!-- main -->
          <div style="display: flex; width: 100%;">

              <!-- main中的左边部分 -->
              <div class="left-part" style="flex: 1;" v-if="!showEmptyResume">
                  <main-resume @formUpdated="refreshData1" @formDeleted="refreshDataDeleted" :defaultForm="resumes[activeIndex-1]"></main-resume>
              </div>

              <div class="left-part" style="flex: 1;" v-else>
                  <empty-resume @formUpdated="refreshData2"></empty-resume>
              </div>


              <!-- main中的右边部分 -->
              <div class="right-part" style="flex: 1;margin-right: 10px;" ref="rightResumePart" v-if="showRightPart">
                  <div class="main">
                      <div class="resume-layout" style="background-color: #e6f7ff;">
                          <div class="section" style="display: flex; justify-content: space-between; align-items: flex-start;">
                              <div style="display: flex; flex-direction: column;">
                                  <div class="name">{{ resumes[activeIndex-1]?.name }}</div>
                                  <div class="contact-info">
                                      <div>
                                          <i class="el-icon-phone-outline"></i>
                                          &nbsp;
                                          <span>{{ resumes[activeIndex-1]?.phoneNumber }}</span>
                                      </div>
                                      <div>
                                          <i class="el-icon-message"></i>
                                          &nbsp;
                                          <span>{{ resumes[activeIndex-1]?.email }}</span>
                                      </div>
                                  </div>
                              </div>

                              <img
                                  style="width: 100px; height: 100px;margin-left: 80px;"
                                  v-bind:src="resumes[activeIndex-1]?.pictureBase64"
                              />
                          </div>
                          
                          
                          <div class="section">
                              <div class="green-line"></div>
                              <div class="title">求职意向</div>
                              <div class="content">{{ resumes[activeIndex-1]?.intention }}</div>
                          </div>

                          <div class="section">
                            <div class="green-line"></div>
                            <div class="title">个人能力</div>
                            <div class="content">
                              <div v-for="(ability, index) in resumes[activeIndex-1]?.abilities" :key="index">
                                {{ ability }}
                              </div>
                            </div>
                          </div>

                          <div class="section">
                              <div class="green-line"></div>
                              <div class="title">教育背景</div>
                              <div class="content">{{ resumes[activeIndex-1]?.background }}</div>
                          </div>
                          <div class="section">
                            <div class="green-line"></div>
                            <div class="title">工作经验</div>
                            <div class="content">
                              <div v-for="(exp, index) in resumes[activeIndex-1]?.experience" :key="index">
                                {{ exp }}
                              </div>
                            </div>
                          </div>
                          
                          
                          
                      </div>
                  </div>
              </div>


          </div>
      </div>
    </div>
  </div>
</template>

<script>
import mainResume from '../../components/resume/mainResume.vue';
import axios from 'axios';
import EmptyResume from '../../components/resume/emptyResume.vue';
import html2pdf from "html2pdf.js";
export default {
components: { mainResume, EmptyResume },
  data() {
    return {
      activeIndex: "1", // 初始简历索引为0
      resumes: [],
      showEmptyResume: false,
      showRightPart: true,
    };
  },
  mounted() {
  this.fetchResumes();
  },
  methods: {
  async fetchResumes() {
    try {
      const response = await axios.get(`http://localhost:8080/resume/user/${this.$store.state.id}`, {
        });
      const data = response.data.data;

      // 将图片 URL 转换为 base64
      for (let resume of data) {
        if (resume.picture) {
          const imageResponse = await axios.get(resume.picture, { responseType: 'arraybuffer' });
          const base64 = btoa(
            new Uint8Array(imageResponse.data).reduce(
              (data, byte) => data + String.fromCharCode(byte), ''
            )
          );
          resume.pictureBase64 = `data:image/jpeg;base64,${base64}`;
        }

        if (typeof resume.abilities === "string") {
          resume.abilities = resume.abilities.split("\n");
        }
        if (typeof resume.experience === "string") {
          resume.experience = resume.experience.split("\n");
        }
      }
      this.resumes = data;
      console.log(this.resumes);
    } catch (error) {
      console.error('获取简历数据失败', error);
    }
  },
  // 选择简历事件
  handleSelect(index) {
    console.log('选择了简历：', index);
    this.activeIndex = index ;
    this.showEmptyResume = false;
    this.showRightPart = true;
  },
  // 当子组件触发 formUpdated 时调用
  refreshData1() {
      this.fetchResumes();
  },
  refreshData2() {
    this.showEmptyResume = false;
    this.showRightPart = true;
    this.fetchResumes().then(() => {
        if (this.resumes.length > 0) {
          this.activeIndex = this.resumes.length;
        } else {
          this.activeIndex = 1;
        }
    });
  },
  refreshDataDeleted(){
    this.fetchResumes();
    this.activeIndex = 1;
  },
  switchToEmptyResume() {
    this.showEmptyResume = true;
    this.showRightPart = false;
  },
  async generatePdf() {
      console.log("已执行 generatePdf");
      const element = this.$refs.rightResumePart;
      const options = {
        margin: 10, // 边距
        filename: 'resume.pdf',
        image: { type: 'jpg', quality: 0.98 }, // 图片质量
        html2canvas: { scale: 2 }, // 提高清晰度
        jsPDF: { unit: 'mm', format: 'a5', orientation: 'landscape' },
      };
      options.jsPDF.autoPaging = 'auto';

      try {
        const pdf = await html2pdf()
                    .set(options)
                    .from(element)
                    .save("resume")
                    .outputPdf('blob');

        const resumeId = this.resumes[this.activeIndex - 1].id;
        const formData = new FormData();
        formData.append('file', pdf); // 直接使用生成的 PDF Blob
        const response = await axios.post(`http://localhost:8080/resume/resume_url/${resumeId}`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        console.log(response.data);
      } catch (error) {
        console.error('上传pdf错误:', error);
      }
    }

},
};
</script>

<style scoped>
.container {
  display: flex;
  height: 100vh;
}
.left {
  flex: 2;
  display: flex;
  flex-direction: column;
  padding: 10px;
}
.right {
  flex: 8;
  padding: 10px;
}
.nav-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  height: 48px;
  background-color: #f0f0f0;
  width: 100%;
}
.resume-layout {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.section {
  text-align: left;
  margin-bottom: 20px;
}
.name {
  font-size: 40px;
  font-weight: bold;
}
.contact-info {
  font-size: 16px;
}
.title {
  font-size: 24px;
  font-weight: bold;
  text-transform: uppercase;
}
.content {
  font-size: 18px;
}
.green-line {
  width: 5px;
  height: 20px;
  background-color: rgb(20, 203, 20);
  margin-right: 10px;
  display: inline-block;
  vertical-align: middle;
}
.title {
  display: inline-block;
  vertical-align: middle;
}
</style>
